<?php
namespace app\admin\controller;
use think\Db;
use think\Request;
use think\Controller;
use clt\Tree;
class Aricle extends Common
{
    
 
    public function index()
    {
       $request = Request::instance();
       $key=$request->only(['key']);
        if($key){
		 $key = $key['key'];
        }else{
		 $key ='';
        }
        $this->assign('testkey',$key);        $map =[]; if (session('aid')!=1){              $map['user_id']=session('aid');            }  	
	    $list = db::view('category',['catname'=>'name'])
		    ->view('aricle','*','aricle.c_id=category.id')
			->where('aricle.title','like',"%".$key."%")            ->where($map)
			->order('addtime desc')
			->paginate(10,false,['query' => request()->param()]);
		

        $page = $list->render();
  	

        $this->assign('page', $page);
        $cate = db('ariclecate')->select();
		$this->assign('cate',$cate);
	   
	   
	   
        $this->assign('list',$list);
    	return view();
    }
	
	

	public function CycleData($parent_id=0){
        $where['pid'] = $parent_id;
        $res = db('ariclecate')->where($where)->select();;
        if(empty($res)) return false;
        foreach($res as $k=>$v){
            $result[$v['id']]['id'] = $v['id'];
            $result[$v['id']]['title'] = $v['title'];
            $result[$v['id']]['pid'] = $v['pid'];
            $rf = $this->CycleData($v['id']);
            if($rf){
                foreach($rf as $k=>$vv){
                    $result[$vv['id']]['id'] = $vv['id'];
                    $result[$vv['id']]['title'] = "   |— ".$vv['title'];
                    $result[$vv['id']]['pid'] = $vv['pid'];
                }
            }
        }
        return $result;
    }
	
	
	
public function add(){
	  if(request()->isPost()) {
            //构建数组
            $data = input('post.');
	        $user = session('user');	                  $data['user_id'] = $user['admin_id'];
			$data['images'] = json_encode($data['images']);
            $data['addtime'] = date("Y-m-d H:i:s",time());
            db('aricle')->insert($data);
            
		   $this->redirect('index'); 
			 


        }else{
        	
			 //栏目选择列表
        foreach($this->categorys as $r) {
            $array[] = $r;
        }

        $str  = "<option value='\$id' \$selected>\$spacer \$catname</option>";
        $tree = new Tree ($array);
        $categorys = $tree->get_tree(0, $str,$parentid);
        $this->assign('categorys', $categorys);
			
        //	$list =  $this->CycleData();
		//	$this->assign('cate',$list);
            $this->assign('info','null');
	        return view();
		}
}

public function edit(){
	
	
        if(request()->isPost()) {
            $data = input('post.');
			
		   $aricle = db('aricle')->where('id',$data['id'])->find();
		  
			if($data['img']){
				if($aricle['img']){
				$root=   ROOT_PATH . 'public' . DS .$aricle['img'];
				if(file_exists($root)){

					unlink($root);
				}
				}
			}else{
				
				$data['img'] =  $aricle ['img'];
			}
			
			
			
			$images = json_decode($aricle['images']);
		if(isset($data['images'])){
			for($i=0;$i<count($images);$i++){
				
				array_push($data['images'],$images[$i]);
			}
			$data['images'] = json_encode($data['images']);
			}
			
			
            db('aricle')->update($data);
           $this->redirect('index'); 
        }else{
            $id=input('id');
			
			
	$result = $this->categorys;
      
   
            $info=db('aricle')->where(array('id'=>$id))->find();
			
			  foreach($result as $r) {
            if($r['type']==1) continue;
            $r['selected'] = $r['id'] == $info['c_id'] ? 'selected' : '';
            $array[] = $r;
        }
        $str  = "<option value='\$id' \$selected>\$spacer \$catname</option>";
        $tree = new Tree ($array);
        $categorys = $tree->get_tree(0, $str,$info['c_id']);
        $this->assign('categorys', $categorys);
			
			
            $this->assign('info',$info);
        
	        $this->assign('images',json_decode($info['images']));   
		
		
            return view();
        }
    
	
}

public function del(){
	$aricle =  db('aricle')->where('id',input('param.id'))->find();
	 db('aricle')->where('id',input('param.id'))->delete();
	 //删除文章。删除图片
	 if($aricle['img']){
	 	$root=   ROOT_PATH . 'public' . DS .$aricle['img'];
		 if($aricle['img']){
		if(file_exists($root)){
			unlink($root);
		}
		 }
	 }

	  if($aricle['images'] != "null"){
	  	foreach(json_decode($aricle['images'])   as $value){
	 	$root=   ROOT_PATH . 'public' . DS .$value;
		if($value){
		if(file_exists($root)){
			unlink($root);
		}
		}
		}
	 }
	 
        $this->redirect('index');
	
}
public function zhiding(){
	
	 $data['id'] = input('param.id');
	 $data['iszhiding'] = input('param.value');	 	  $jiangpin['good_id'] = input('param.id');	  	$info =  db('aricle')->find($data['id']);	  $jiangpin['name'] = $info['title'];	    $jiangpin['user_id'] = $info['user_id'];     if($data['iszhiding'] == 0){     	  db('jiangpin')->delete($jiangpin);     }else{     	  db('jiangpin')->insert($jiangpin);     }      
	
	 db('aricle')->update($data);
	 $this->redirect('index');
}public function tuijian(){		 $data['id'] = input('param.id');	 $data['iszd'] = input('param.value');	 	  	  	      		 db('aricle')->update($data);	 $this->redirect('index');}





public function upload(){

    $files = request()->file();
    foreach($files as $file){
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->rule('uniqid')->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){
            // 成功上传后 获取上传信息
            // 输出 jpg
              $path =  $info->getFilename();

              return "/uploads/".$path;
         
        }else{
            // 上传失败获取错误信息
            echo $file->getError();
        }    
    }
 	
	}

	//删除图片
	public function deleteimages(){
		$id = $_POST['id'];
		$name = $_POST['name'];
		
		$user = db('aricle');
		$data = $user->where('id='.$id)->find();
		$images = json_decode($data['images']);
	
		$data2['images'] = array();
		foreach($images as $value){
			
			if($name != $value){
				array_push($data2['images'],$value);
			}
			
		}
			
		
		$data2['id'] = $id;
	$data2['images'] = json_encode($data2['images']);
	 $result =	$user->update($data2);
	 
	 if($result){
	 	$path = ROOT_PATH . 'public' . DS .$name;
	 	 if(file_exists($path)){
	 	 	unlink($path);
	 	 }
		//更新成功
		return 1;
	 }else{
	 	
		return 0;
	 }	
		
	}public function addshuxing(){	if(request()->isPost()){        $result =input('post.');        $redata = array();         foreach($result as $key=>$value){         	         	 $key = str_replace('_','.',$key);         	$redata[$key]=$value;         }                           foreach( $redata as $key=>$value){        	if($key=='lv1'){        		$data['shuxing'] = $redata[$key];        		        	}else if($key=='id'){        				$data['id']= $redata[$key];        	}else{        		$data['value'][$key]= $redata[$key];        	}        	        }				$data['shuxing'] = json_encode($data['shuxing']);		$data['value'] = json_encode($data['value']);						db('aricle')->update($data);		$this->redirect('index');			}		$request = Request::instance();    $result =$request->param();    $data = db('aricle')->where($result)->find();    $this->assign('data',$data);           if($data['shuxing'] !="null" && $data['value'] !="null"){    	    	$shuxing = json_decode($data['shuxing']);    	    	     	$sv = json_decode($data['value']);    	    	$aaa = [];    	    	 for($i=0;$i<count($shuxing);$i++){    	          $aaa[$i]['shuxing'] = $shuxing[$i];    	 	    $aaa[$i]['child'] = array();    	 	foreach($sv  as $k=>$v){    	 		    	 		$cc = explode(':',$k);     	 		if(!in_array($cc[$i], $aaa[$i]['child'])){    	 			array_push($aaa[$i]['child'],$cc[$i]);    	 			    	 		}    	 		    	 		    	 	}    	 	    	 	    	 	    	 }    	     	 $this->assign('shuxing',$aaa);    	    }   if($data['value'] !="null"  && $data['value'] ){   	     $value = json_decode($data['value']);             $htmls =[];             foreach($value as $key=>$value){    	$aa = explode(':',$key);     	    	$text = '';    	for($i=0;$i<count($aa);$i++){    		    		$text = $text."<td width='50'>".$aa[$i]."</td>";    		    	}            	$html = "<tr data-row='1'>".$text."    	<td width='20'><input type='text' name='".$key."[price]' value='".$value->price."'></td>	<td width='20'><input type='text' name='".$key."[original_price]'  value='".$value->original_price."' ></td></tr>";    	array_push($htmls,$html);    }    $this->assign('htmls',$htmls);}    	return view();}
   
}
